/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pig.generator.controller;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.generator.entity.OmsCartItem;
import com.pig4cloud.pig.generator.entity.PmsProduct;
import com.pig4cloud.pig.generator.service.PmsProductService;
import com.pig4cloud.pig.generator.utils.QiniuUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.bouncycastle.cert.ocsp.Req;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.ElasticsearchClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateDataStreamRequest;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.DeleteAliasRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import javax.servlet.http.HttpServletRequest;


/**
 * 商品表
 *
 * @author pig code generator
 * @date 2021-07-16 09:58:00
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/pmsproduct" )
@Api(value = "pmsproduct", tags = "商品表管理")
public class PmsProductController {

    private final  PmsProductService pmsProductService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
	private RestHighLevelClient restHighLevelClient;




    /**
     * 分页查询
     * @param page 分页对象
     * @param pmsProduct 商品表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('generator_pmsproduct_get')" )
    public R getPmsProductPage(Page page, PmsProduct pmsProduct) {
        return R.ok(pmsProductService.page(page, Wrappers.query(pmsProduct)));
    }

    @GetMapping("/list")
	public R list(PmsProduct pmsProduct) throws IOException, InterruptedException {
		String name = pmsProduct.getName();
		System.out.println(name+"111111111111111");
		GetIndexRequest request=new GetIndexRequest("shop");
		boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
		if(exists){
			//从es库获取
			SearchRequest shop=new SearchRequest("shop");
			SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
			if(pmsProduct.getName()==null||pmsProduct.getName().equals("")){
				searchSourceBuilder.query(QueryBuilders.matchAllQuery());
			}else{
				searchSourceBuilder.query(QueryBuilders.multiMatchQuery(pmsProduct.getName(),"name"));
				HighlightBuilder highlightBuilder=new HighlightBuilder();
				System.out.println("开始查询了？？？？？？？？？？？？？");
				highlightBuilder.field("name");
				highlightBuilder.preTags("<span style=\"color: red\">");
				highlightBuilder.postTags("</span>");
				searchSourceBuilder.highlighter(highlightBuilder);
			}
			//放入请求
			shop.source(searchSourceBuilder);
			System.out.println("es搜索了");
			//开始es搜索
			SearchResponse search = restHighLevelClient.search(shop, RequestOptions.DEFAULT);
			SearchHit[] hits=search.getHits().getHits();
			ArrayList<Map<String, Object>> lists = new ArrayList<>();
			for (SearchHit hit : hits) {
				Map<String, HighlightField> highlightFields=hit.getHighlightFields();
				HighlightField pname = highlightFields.get("name");
				Map<String, Object> sourceAsMap = hit.getSourceAsMap();
				if(pname!=null){
					Text[] fragments = pname.fragments();
					String ntitles="";
					for (Text fragment:fragments){
						ntitles+=fragment;
					}
					sourceAsMap.put("name",ntitles);
				}
				lists.add(sourceAsMap);

			}
			return R.ok(lists);
		}else{
			CreateIndexRequest request1 = new CreateIndexRequest("shop");
			restHighLevelClient.indices().create(request1,RequestOptions.DEFAULT);
			List<PmsProduct> getlist = pmsProductService.getlist(pmsProduct);
			System.out.println(getlist.get(0)+"查询出来的数据");
			for (PmsProduct product:getlist){
				IndexRequest shop=new IndexRequest("shop");
				shop.source(JSON.toJSONString(product), XContentType.JSON);
				shop.id(String.valueOf(product.getId()));
				restHighLevelClient.index(shop,RequestOptions.DEFAULT);
			}
			System.out.println("es库新建完成===============================");

			//es库获取
			SearchRequest shop = new SearchRequest("shop");
			SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
			searchSourceBuilder.query(QueryBuilders.matchAllQuery());
			SearchResponse search = restHighLevelClient.search(shop, RequestOptions.DEFAULT);
			SearchHit[] hits = search.getHits().getHits();
			ArrayList<Map<String, Object>> lists = new ArrayList<>();
			for (SearchHit hit : hits) {
				Map<String, Object> sourceAsMap = hit.getSourceAsMap();
				lists.add(sourceAsMap);
			}
			System.out.println("es库查找完成==========================");
			System.out.println(lists);
			return R.ok(lists);
		}


	}

    /**
     * 通过id查询商品表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('generator_pmsproduct_get')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(pmsProductService.getById(id));
    }

    /**
     * 新增商品表
     * @param pmsProduct 商品表
     * @return R
     */
    @ApiOperation(value = "新增商品表", notes = "新增商品表")
    @SysLog("新增商品表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('generator_pmsproduct_add')" )
    public R save(@RequestBody PmsProduct pmsProduct) {
        return R.ok(pmsProductService.save(pmsProduct));
    }

    /**
     * 修改商品表
     * @param pmsProduct 商品表
     * @return R
     */
    @ApiOperation(value = "修改商品表", notes = "修改商品表")
    @SysLog("修改商品表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('generator_pmsproduct_edit')" )
    public R updateById(@RequestBody PmsProduct pmsProduct) {
        return R.ok(pmsProductService.updateById(pmsProduct));
    }

    /**
     * 通过id删除商品表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除商品表", notes = "通过id删除商品表")
    @SysLog("通过id删除商品表" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('generator_pmsproduct_del')" )
    public R removeById(@PathVariable Long id) {
        return R.ok(pmsProductService.removeById(id));
    }


    @ResponseBody
	@PostMapping("/uploadImg" )
	public R uploadImg(@RequestParam("file") MultipartFile image) throws IOException {
		String filename = image.getOriginalFilename();
		String s = QiniuUtil.uploadQiNiu(image.getBytes(), filename);
		return R.ok(s);
	}

	//加入购物车
	@RequestMapping("addCart")
	public boolean addCart(Long id) {
		OmsCartItem oms=new OmsCartItem();

		//前端获取ID,通过ID查询对应的数据放入到Redis中
		QueryWrapper<PmsProduct> queryWrapper=new QueryWrapper<>();
		queryWrapper.eq("id",id);
		List<PmsProduct> list = pmsProductService.list(queryWrapper);
		PmsProduct pmsProduct = list.get(0);
		System.out.println(pmsProduct+"11111111111111");

		int car=0;
    	//获取当前用户ID
		PigUser user = SecurityUtils.getUser();
		System.out.println(user.getId()+"zheshi ");
		HashOperations hashOperations=redisTemplate.opsForHash();
		Set<String> keys = hashOperations.keys(String.valueOf(user.getId()));

		if(keys!=null && keys.size()>0){
			for (String key : keys){
				if(key.equals(String.valueOf(id))){
					OmsCartItem o= (OmsCartItem) hashOperations.get(String.valueOf(user.getId()),String.valueOf(key));
					o.setQuantity(o.getQuantity()+1);
					hashOperations.put(String.valueOf(user.getId()),String.valueOf(key),o);
					car=car+1;
					OmsCartItem o1= (OmsCartItem) hashOperations.get(String.valueOf(user.getId()),String.valueOf(key));
					System.out.println(o1);
				}
			}
		}else{
			car=car+1;
			oms.setProductId(id);
			oms.setProductName(pmsProduct.getName());
			oms.setQuantity(1);
			hashOperations.put(String.valueOf(user.getId()),String.valueOf(id),oms);
		}
		if(car==0){
			oms.setProductId(id);
			oms.setProductName(pmsProduct.getName());
			oms.setQuantity(1);
			hashOperations.put(String.valueOf(user.getId()),String.valueOf(id),oms);
		}




		return true;
	}

	//上架下架操作
	@RequestMapping("/jia")
	public HashMap<String,Object> jia(PmsProduct pmsProduct) throws IOException, TemplateException {

		//创建配置对象
		Configuration configuration = new Configuration(Configuration.getVersion());
		//设置默认生成文件编码
		configuration.setDefaultEncoding("utf-8");
		//设置模板路径
		configuration.setClassForTemplateLoading(this.getClass(), "/templates");
		//获取模板
		Template template = configuration.getTemplate("index.ftl");
		HashMap<String,Object> map=new HashMap<>();
    	System.out.println(pmsProduct+"ppppppp");

    	map.put("name",pmsProduct.getName());
		map.put("price",pmsProduct.getPrice());
		map.put("description",pmsProduct.getDescription());
		map.put("pic",pmsProduct.getPic());
		map.put("id",pmsProduct.getId());

		if(pmsProduct.getPublishStatus().equals("1")){
			FileWriter fileWriter=new FileWriter("D:/"+pmsProduct.getId()+".html");

			template.process(map,fileWriter);
			String filename = UUID.randomUUID().toString()+".html";
			byte[] bytes = Files.readAllBytes(new File("D:/" + pmsProduct.getId() + ".html").toPath());
			System.out.println("++++++++++++++++++++++++++++++++++++");
			String s = QiniuUtil.uploadQiNiu(bytes, filename);
			System.out.println(s+"七牛云");
			pmsProduct.setDetailHtml(s);


			fileWriter.close();
		}
		PmsProduct byId = pmsProductService.getById(pmsProduct.getId());

		String publishStatus = byId.getPublishStatus();
			System.out.println(publishStatus+"打印状态");
			if(publishStatus.equals("0")){
				IndexRequest request=new IndexRequest("shop");
				request.source(JSON.toJSONString(byId),XContentType.JSON);
				System.out.println("666666");
				request.id(String.valueOf(byId.getId()));
				restHighLevelClient.index(request,RequestOptions.DEFAULT);
			}else {
				DeleteRequest request=new DeleteRequest("shop",String.valueOf(byId.getId()));
				restHighLevelClient.delete(request,RequestOptions.DEFAULT);
			}

			pmsProductService.updateById(pmsProduct);
			map.put("code",200);
			map.put("message","修改成功");
		return map;
	}
}
